/**
 * @file serverplayer.cpp
 * @brief ServerPlayer class methods implementation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3 of the License.
 *
 * @author VestniK (Sergey N.Vidyuk) sir.vestnik@gmail.com
 * @date 16 Oct 2008
 */
#include "serverplayer.h"

#include "game.h"
#include "mjntypes.h"
#include "sessionfactory.h"

using namespace mjn;

ServerPlayer::ServerPlayer(Game* game): QObject(game) {
   mGame = game;
   mPlayerScore = 0;
   mMyTurn = false;
   mName = "player";
}

void ServerPlayer::setName(const QString &name) {
    mName = name;
    emit updated();
}

/**
 * Takes tiles from the wall and sends the new round notification to the client.
 */
void ServerPlayer::beginRound() {
   mHand.clear();
   for ( int i = 0; i < HAND_SIZE; i++ ) {
      mHand.append( mGame->wall().takeTile() );
   }
   if ( mPlayerWind == East ) {
      mHand.append( mGame->wall().takeTile() );
   }
   emit startOfRound(mPlayerWind,mGame->wind(),mHand);
}

void ServerPlayer::makeTurn(bool firstTurn) {
   if ( firstTurn ) {
      mTileTaken = true;
   } else {
      mTileTaken = false;
   }
   mMyTurn = true;
   emit startOfTurn();
}

/**
 * @param discardedTile ID of the tile to discard
 */
void ServerPlayer::endTurn(TileID discardedTile) {
   if ( ! mHand.removeOne(discardedTile) ) {
      emit riseError("Can't discard tile not from my hand");
      return;
   }
   mMyTurn = false;
   mGame->nextTurn(discardedTile);
}


void ServerPlayer::takeTileFromWall() {
   if ( ! mMyTurn ) {
      emit riseError("It's not your turn to take a tile.");
      return;
   }
   if ( mTileTaken ) {
      riseError("Tile have been already taken. Can't take another one.");
      return;
   }
   TileID takenTile = mGame->wall().takeTile();
   mHand.append( takenTile );
   mTileTaken = true;
   emit tileTaken(takenTile);
}

void ServerPlayer::takeDiscardedTile() {
   if ( ! mMyTurn ) {
      emit riseError("It's not your turn to take a tile");
      return;
   }
   if ( mTileTaken ) {
      emit riseError("Tile have been already taken. Can't take another one.");
      return;
   }
   TileID takenTile = mGame->takeDiscardedTile();
   if ( takenTile == NULL_TILE_ID ) {
      emit riseError("There is no discarded tile. You can't take it.");
      return;
   }
   mHand.append( takenTile );
   mTileTaken = true;
   emit tileTaken(takenTile);
}
